const { ipcMain, dialog } = require('electron');
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const ExcelJS = require('exceljs');
const csv = require('csv-parser');
const crypto = require('crypto'); // 用于计算表头指纹

function registerFileHandlers() {
    // 1. 选择导出路径
    ipcMain.handle('select-export-path', async () => {
        const result = await dialog.showOpenDialog({
            properties: ['openDirectory', 'createDirectory']
        });
        return result.canceled ? null : result.filePaths[0];
    });

    // 2. 选择导入文件 (支持多选)
    ipcMain.handle('select-import-file', async (event, options = {}) => {
        const result = await dialog.showOpenDialog({
            title: options.title || '选择文件 (支持多选)',
            properties: ['openFile', 'multiSelections'], // 开启多选
            filters: options.filters || []
        });
        return result.canceled ? [] : result.filePaths; // 返回数组
    });

    // 3. 选择保存文件
    ipcMain.handle('select-save-file', async (event, options = {}) => {
        const result = await dialog.showSaveDialog({
            title: options.title || '保存文件',
            defaultPath: options.defaultPath,
            filters: options.filters || []
        });
        return result.canceled ? null : result.filePath;
    });

    // 4. 读取文本文件
    ipcMain.handle('read-text-file', async (event, filePath) => {
        return await fs.readFile(filePath, 'utf8');
    });

    // 5. [新增] 嗅探文件结构 (只读表头，用于分组)
    ipcMain.handle('inspect-files', async (event, filePaths) => {
        const results = [];
        console.log(`[Inspector] 开始扫描 ${filePaths.length} 个文件...`);

        for (const filePath of filePaths) {
            const ext = path.extname(filePath).toLowerCase();
            const fileName = path.basename(filePath);

            try {
                if (ext === '.xlsx' || ext === '.xls') {
                    const workbook = new ExcelJS.Workbook();
                    // 读取文件
                    await workbook.xlsx.readFile(filePath);

                    workbook.eachSheet((worksheet, sheetId) => {
                        // 获取第一行作为表头
                        const firstRow = worksheet.getRow(1);
                        const headers = [];
                        firstRow.eachCell((cell) => {
                            const val = cell.value ? cell.value.toString().trim() : '';
                            if (val) headers.push(val);
                        });

                        if (headers.length > 0) {
                            // 计算表头指纹 (MD5)
                            const headerStr = headers.join('|');
                            const signature = crypto.createHash('md5').update(headerStr).digest('hex');

                            results.push({
                                filePath,
                                fileName,
                                sheetName: worksheet.name,
                                headers: headers,
                                signature: signature,
                                rowCount: worksheet.rowCount
                            });
                        }
                    });
                } else if (ext === '.csv') {
                    // CSV 处理逻辑
                    await new Promise((resolve) => {
                        const stream = fsSync.createReadStream(filePath).pipe(csv());
                        stream.on('headers', (headerList) => {
                            const headers = headerList.map(h => h.trim()).filter(h => h);
                            if (headers.length > 0) {
                                const signature = crypto.createHash('md5').update(headers.join('|')).digest('hex');
                                results.push({
                                    filePath,
                                    fileName,
                                    sheetName: 'CSV',
                                    headers: headers,
                                    signature: signature,
                                    rowCount: 0
                                });
                            }
                            stream.destroy(); // 读完头就关闭
                            resolve();
                        });
                        stream.on('error', (err) => {
                            console.error('CSV读取错误:', err);
                            resolve();
                        });
                        stream.on('end', resolve);
                    });
                }
            } catch (e) {
                console.error(`嗅探失败: ${filePath}`, e);
                results.push({ filePath, fileName, error: e.message });
            }
        }
        return results;
    });

    // 6. 解析文件 (全量读取，支持指定Sheet)
    ipcMain.handle('parse-file', async (event, { filePath, dataType, options }) => {
        options = options || {};
        const targetSheetName = options.sheetName;

        try {
            const ext = path.extname(filePath).toLowerCase();
            const results = [];
            let headers = [];

            if (ext === '.xlsx' || ext === '.xls') {
                const workbook = new ExcelJS.Workbook();
                await workbook.xlsx.readFile(filePath);

                let worksheet;
                if (targetSheetName) {
                    worksheet = workbook.getWorksheet(targetSheetName);
                } else {
                    worksheet = workbook.worksheets.find(ws => ws.state === 'visible') || workbook.getWorksheet(1);
                }

                if (!worksheet) {
                    return { success: false, message: `找不到工作表: ${targetSheetName || '默认'}` };
                }

                const headerMap = {};
                const headerRow = worksheet.getRow(1);
                headerRow.eachCell((cell, colNumber) => {
                    const val = cell.value ? cell.value.toString().trim() : '';
                    if (val) {
                        headerMap[colNumber] = val;
                        headers.push(val);
                    }
                });

                worksheet.eachRow((row, rowNumber) => {
                    if (rowNumber === 1) return;
                    const rowData = {};
                    let hasData = false;
                    row.eachCell((cell, colNumber) => {
                        const header = headerMap[colNumber];
                        if (header) {
                            let value = cell.value;
                            if (value !== null && value !== undefined) {
                                if (typeof value === 'object') {
                                    if (value instanceof Date) value = value.toISOString();
                                    else if (value.text) value = value.text;
                                    else if (value.result !== undefined) value = value.result;
                                    else if (value.richText) value = value.richText.map(t => t.text).join('');
                                }
                                const strVal = String(value).trim();
                                if (strVal !== '') {
                                    rowData[header] = strVal;
                                    hasData = true;
                                }
                            }
                        }
                    });
                    if (hasData) results.push(rowData);
                });
            } else if (ext === '.csv') {
                await new Promise((resolve, reject) => {
                    fsSync.createReadStream(filePath).pipe(csv())
                        .on('headers', h => headers = h)
                        .on('data', data => results.push(data))
                        .on('end', resolve)
                        .on('error', reject);
                });
            } else {
                return { success: false, message: `不支持的文件格式: ${ext}` };
            }

            return {
                success: true,
                fullData: results,
                previewData: results.slice(0, 50),
                availableFields: headers,
                totalRecords: results.length
            };

        } catch (error) {
            console.error('File parse error:', error);
            return { success: false, message: `解析失败: ${error.message}` };
        }
    });

    // 导出数据
    ipcMain.handle('export-data', async (event, { data, filePath, dataType }) => {
        try {
            const workbook = new ExcelJS.Workbook();
            const worksheet = workbook.addWorksheet(dataType || 'Sheet1');

            if (!data || data.length === 0) {
                await workbook.xlsx.writeFile(filePath);
                return { success: true };
            }

            const keys = Object.keys(data[0]);
            worksheet.addRow(keys);
            worksheet.getRow(1).font = { bold: true };

            data.forEach(item => {
                const row = [];
                keys.forEach(key => row.push(item[key]));
                worksheet.addRow(row);
            });

            await workbook.xlsx.writeFile(filePath);
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    });
}

module.exports = { registerFileHandlers };